import React, { useState, useEffect, useRef } from 'react'
import { Row, Col, Card, List, Avatar, Drawer } from 'antd'
import { EditOutlined, EllipsisOutlined, SettingOutlined } from '@ant-design/icons';
import axios from 'axios'
import * as echarts from 'echarts';
import _ from 'lodash'

const { Meta } = Card;

export default function Home(props) {
    // 获取token值,解构对象
    const { username, region, role: { roleName } } = JSON.parse(localStorage.getItem("token"))
    // 用户最常浏览新闻排行
    const [frequentlydData, setFrequentlydData] = useState([])
    // 点赞最多数据新闻排行
    const [mostLikesData, setMostLikesData] = useState([])
    // 抽屉按钮状态
    const [drawerState, setDrawerState] = useState(false);
    // 判断饼状图数据存在，是否渲染
    const [pieChart, setPieChart] = useState(null)
    // 柱状图Ref
    const HistogramRef = useRef(null)
    // 饼状图数据
    const [allList, setAllList] = useState([])
    // 饼状图REF
    const pieRef = useRef(null)

    // 获取用户最常浏览排行
    useEffect(() => {
        axios.get("/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=8").then(res => {
            setFrequentlydData(res.data)
        })
    }, [])

    // 获取点赞最多排行
    useEffect(() => {
        axios.get("/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=8").then(res => {
            // console.log(res.data)
            setMostLikesData(res.data)
        })
    }, [])

    // 获取表格数据
    useEffect(() => {
        axios.get("/news?publishState=2&_expand=category").then(res => {
            renderBarView(_.groupBy(res.data, item => item.category.title))
            setAllList(res.data)
            // renderPieView()
        })
        return () => {
            window.onresize = null
        }
    }, [])

    // 配置柱形图表格参数数据
    const renderBarView = (obj) => {
        // 基于准备好的dom，初始化echarts实例
        let myChart = echarts.init(HistogramRef.current);

        // 指定图表的配置项和数据
        const option = {
            title: {
                text: '新闻分类图示'
            },
            tooltip: {},
            legend: {
                data: ['数量']
            },
            xAxis: {
                data: Object.keys(obj),
                axisLabel: {
                    rotate: "0",
                    interval: 0
                }
            },
            yAxis: {
                minInterval: 2
            },
            series: [
                {
                    name: '数量',
                    type: 'bar',
                    data: Object.values(obj).map(item => item.length)
                }
            ]
        }
        // 绘制图表
        myChart.setOption(option);
        window.onresize = () => {
            // console.log("resize")
            myChart.resize()
        }
    }

    // 配置饼形图表格参数数据
    const renderPieView = () => {
        let currentList = allList.filter(item => item.author === username)
        let groupObj = _.groupBy(currentList, item => item.category.title)
        let list = []
        for (let i in groupObj) {
            list.push({
                name: i,
                value: groupObj[i].length
            })
        }
        // 基于准备好的dom，初始化echarts实例
        let myChart
        if (!pieChart) {
            myChart = echarts.init(pieRef.current);
            setPieChart(myChart)
        } else {
            myChart = pieChart
        }

        // 指定饼图表的配置项和数据
        let option = {
            title: {
                text: '当前用户新闻分类图示',
                // subtext: 'Fake Data',
                left: 'center'
            },
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '发布数量',
                    type: 'pie',
                    radius: '50%',
                    data: list,
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        // 绘制图表
        option && myChart.setOption(option);
    }

    return (
        <div>
            <Row gutter={16}>
                <Col span={8}>
                    <Card
                        title="用户最常浏览"
                        bordered={true}
                    >
                        <List
                            itemLayout="horizontal"
                            dataSource={frequentlydData}
                            renderItem={(item, index) => (
                                <List.Item>
                                    <List.Item.Meta
                                        avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />}
                                        title={<a style={{ color: "#00c4ff" }} href={`#/news-manage/preview/${item.id}`}>{item.title}</a>}
                                    />
                                </List.Item>
                            )}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card
                        title="用户点赞最多"
                        bordered={true}
                    >
                        <List
                            itemLayout="horizontal"
                            dataSource={mostLikesData}
                            renderItem={(item, index) => (
                                <List.Item>
                                    <List.Item.Meta
                                        avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`} />}
                                        title={<a style={{ color: "#056d0d" }} href={`#/news-manage/preview/${item.id}`}>{item.title}</a>}
                                    />
                                </List.Item>
                            )}
                        />
                    </Card>
                </Col>
                <Col span={8}>
                    <Card
                        cover={
                            <img
                                alt="example"
                                src={require("../../../assets/img/ail.jpg")}
                            />
                        }
                        actions={[
                            <SettingOutlined key="setting"
                                onClick={() => {
                                    setTimeout(() => {
                                        // init饼状图初始化
                                        renderPieView()
                                        setDrawerState(true)
                                    }, 10)
                                }}
                            />,
                            <EditOutlined key="edit" onClick={()=>{
                                props.history.push('/user-manage/list')
                            }} />,
                            <EllipsisOutlined key="ellipsis" onClick={()=>{
                                props.history.push('/right-manage/right/list')
                            }} />,
                        ]}
                    >
                        <Meta
                            onClick={() => {
                                setTimeout(() => {
                                    // init饼状图初始化
                                    renderPieView()
                                    setDrawerState(true)
                                }, 10)
                            }}
                            avatar={<Avatar src={require("../../../assets/img/123.jpeg")} />}
                            title={username}
                            description={
                                <div>
                                    <b>{region ? region : "全球"}</b>
                                    <span style={{
                                        paddingLeft: "30px"
                                    }}>{roleName}</span>
                                </div>
                            }
                        />

                    </Card>
                </Col>
            </Row>
            <Drawer title="个人新闻分类" width="550px" onClose={() => {
                setDrawerState(false)
            }} open={drawerState} forceRender={true}>
                <div ref={pieRef} style={{ width: '550px', marginTop: "30px", height: '500px' }}></div>
            </Drawer>
            <div ref={HistogramRef} style={{ width: '100%', marginTop: "30px", height: '400px' }}></div>
            {/* <div ref={pieRef} style={{ width: '100%', marginTop: "30px", height: '400px' }}></div> */}
        </div>
    )
}
